//
//  EMMAppChecker.m
//  EMMApp
//
//  Created by Mac on 16/7/5.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMAppChecker.h"
#define kVgoCurrentVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey]
#define myUrlMethod @"getVersion"
#define myUrlPath @"/appapi/getVersion"

@interface EMMAppChecker () <UIAlertViewDelegate> {
    NSString *_body;
}

@property (nonatomic,strong) NSString *CHANNEL_ID;

@property (nonatomic,strong) NSString *appStoreId;

@property (nonatomic,strong) NSString *umengKey;

@property (strong) NSString *igronUpdateVersion;
@property (strong) NSString *updatePath;
@property (assign) BOOL igronUpdate;
@property (assign) BOOL updateAlert;

@end

@implementation EMMAppChecker
@synthesize igronUpdate,updateAlert,updatePath;
@synthesize appStoreId,umengKey;

static NSObject *lock;

+ (EMMAppChecker *)sharedInstance
{
    static EMMAppChecker *sharedInstance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        sharedInstance = [[EMMAppChecker alloc] init];
        lock =[[NSObject alloc] init];
    });
    
    return sharedInstance;
}


#pragma mark - Public Methods

- (void)startCheckVgoUpdate
{
    if(!updateAlert){
//        NSString *url = @"https://itunes.apple.com/lookup?id=1140472971";
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        [self checkVgoUpdateInMainThread];
    }
}

- (void)checkVgoUpdateInMainThread
{
    @try {
        NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
        NSString *merchantId = [userdf objectForKey:@"merchantId"];
        NSString *userId = [userdf objectForKey:@"userNameId"];
        NSString *token = [userdf objectForKey:@"is_login"];
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setValue:kVgoCurrentVersion forKey:@"version"];
        [params setValue:[IDTools devId2] forKey:@"terminalCode"];
        [params setValue:merchantId forKey:@"merchantId"];
        [params setValue:@"0" forKey:@"versionType"];
        [params setValue:userId forKey:@"userId"];
        [params setValue:token forKey:@"token"];
        
        NSString *json = [@{@"params" : params} JSONString];
        _body = [@{@"params" : params} JSONString];
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        
        NSMutableDictionary *params1 = [NSMutableDictionary dictionary];
        params1[@"body"] = json;
        NSLog(@"%@:\n %@%@?body=%@", myUrlMethod, apiBaseUrl, myUrlPath, _body);
        
        [mgr POST:[NSString stringWithFormat:@"%@/appapi/getVersion", apiBaseUrl]
         
       parameters:params1
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              
              NSLog(@"请求成功 --- %@", responseObject);
              if (responseObject != nil) {
                  NSDictionary *resData = responseObject[@"resData"];
                  if (resData == nil) {
                      resData = responseObject;
                  }
                  
                  NSString *result = resData[@"result"];
                  if (![NSString isStringEmpty:result]&&[result isEqualToString:@"1"]) {
                      NSString *strNewVersion = resData[@"versionNum"];
                      NSString *versionDes = resData[@"versionDes"];
                      NSString *versionStatus = resData[@"versionStatus"];
                      NSString *versionUrlAddress = resData[@"versionUrlAddress"];
                      NSString *versionName = resData[@"versionName"];

                      if (![NSString isStringEmpty:versionStatus]) {
                          NSString *fource_version = nil;
                          // 版本状态：0 不升级；1 可升级；2 强制升级
                          if (versionStatus.integerValue==2) {
                              fource_version = strNewVersion;
                          } else if (versionStatus.integerValue == 0) {
                              return;
                          }
                          
                          NSString *igronUpdateVersion =[[NSUserDefaults standardUserDefaults] stringForKey:@"igronUpdateVe"];
                          
                          if(igronUpdateVersion==nil||(igronUpdateVersion!=nil&&[strNewVersion isNewerVersionThan2:igronUpdateVersion])){
//                              _igronUpdateVersion = strNewVersion;
                              
                              NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                                           kVgoCurrentVersion, @"current_version",
                                                           versionUrlAddress, @"path",
                                                           strNewVersion, @"version",
                                                           versionDes, @"update_log",
                                                           versionName, @"versionName",nil];
                              if (versionStatus.integerValue==2) {
                                  [dict setObject:strNewVersion forKey:@"fource_version"];
                              }
                              [self performSelectorOnMainThread:@selector(callVgoBackUpdate:) withObject:dict waitUntilDone:NO];
                          } else {
                              NSLog(@"igron Update ... ");
                          }
                          
                          
                      }
                      
                  }
                  
              }
              
          }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              
              NSLog(@"请求失败 --- %@",error);
          }];
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[[exception callStackSymbols] componentsJoinedByString:@"\n"]);
    }
}

- (void)callVgoBackUpdate:(NSDictionary *)dic
{
    NSString *fource_version = [dic objectForKey:@"fource_version"];
    
    NSString *version = [dic objectForKey:@"version"];
    
    NSString *current_version = [dic objectForKey:@"current_version"];
    
    NSString *versionName = [dic objectForKey:@"versionName"];
    
    updatePath = [dic objectForKey:@"path"];
    
    //是否有更新
    if([version isNewerVersionThan2:current_version]){
        
        NSString *update_log=[dic objectForKey:@"update_log"];
        
        //强制更新版本与新版本号一致，强制更新
        if(fource_version!=nil&&[fource_version isEqualToString:version]){
            
            if(!updateAlert){
                
                updateAlert = YES;
                
                NSMutableString *versionString =[[NSMutableString alloc] init];
                
                [versionString appendFormat:@"需要您更新版本 v%@",versionName];
                
                UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:versionString message:update_log delegate:self cancelButtonTitle:nil otherButtonTitles:@"点击更新", nil];
                alertView.tag = 10000;
                
                [alertView show];
                
            }
            
        }else{
            if(!updateAlert&&!igronUpdate){
                
                updateAlert = YES;
                
                NSMutableString *versionString = [[NSMutableString alloc] init];
                
                [versionString appendFormat:@"发现新版本 v%@",versionName];
                UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"发现新版本 v%@",versionName] message:update_log delegate:self cancelButtonTitle:@"忽略" otherButtonTitles:@"更新", nil];
                alertView.tag = 20000;
                
                [alertView show];
            }
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(alertView.tag==10000){
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updatePath]];
        
        updatePath = nil;
        exit(0);
        
        return;
    }else{
        if(buttonIndex==0){
            //忽略版本更新，下次启动应用时再提示
            igronUpdate=YES;
            
            [[NSUserDefaults standardUserDefaults] setObject:_igronUpdateVersion forKey:@"igronUpdateVe"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else{
            //直接开始安装：itms-services://
            //网站地址： http://
//
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updatePath]];
            if([updatePath hasPrefix:@"itms-services://"]){
                updatePath =nil;
                exit(0);
            }else{
                igronUpdate = NO;
                updatePath =nil;
            }
        }
    }
    updateAlert = NO;
}
@end
